﻿using System;
using System.Collections.Generic;

namespace Extensions
{
    // 对列表进行随机(洗卡)
    public static class IListExtension
    {
        private static Random _random;

        static IListExtension()
        {
            _random = new Random();
        }

        public static void Shuffle<T>(this IList<T> list)
        {
            var n = list.Count;
            while (n > 1)
            {
                n--;
                var k     = _random.Next(n + 1);
                var value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }

        public static void Replace<T>(this IList<T> list, Predicate<T> oldItemSelector, T newItem)
        {
            for (var i = 0; i < list.Count; ++i)
            {
                if (oldItemSelector(list[i]))
                {
                    list[i] = newItem;
                    return;
                }
            }
        }

        public static int GetRandomIndex<T>(this IList<T> list)
        {
            return _random.Next(list.Count);
        }
    }
}